package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.controller.webSocket.WebSocketServer;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auth: cdz
 * @Desc:
 * @Date: 2023/3/14 11:33
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //一、根据购物车中商品和前端传递的数据，生成一个订单
        //1.属性拷贝，把DTO中属性拷贝到Orders对象
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //2.补全Orders对象中缺少的属性
        /*
         * id --数据库自增
         * number 订单号 --根据毫秒值生成
         * status 订单状态 --默认值
         * userId 用户id --线程获取
         * orderTime 下单时间 --当前时间
         * checkoutTime 结账时间 --待完善
         * payStatus 支付时间 --待完善
         * amount 实付金额 --
         * userName 用户名 --***
         * phone 手机号 --收货地址获取
         * address 地址 --收货地址获取
         * consignee 收货人 --收货地址获取
         * cancelReason 订单取消原因 --用户取消时
         * rejectionReason 订单拒绝原因 --用户拒绝时
         * cancelTime 订单取消时 --用户取消或者超时取消
         * deliveryTime 送达时间 --送达时
         * */
        /*
         id---自增
         status---默认值
         payStatus---默认值
         checkoutTime ---支付完成后完善数据
         cancelReason---用户取消时，完善信息
         rejectionReason---用户拒绝时，完善信息
         cancelTime---用户取消时，完善信息；或者订单超时自动取消，完善信息。
         deliveryTime---骑手送达，点击送达，完善信息
         ---------------------------------------------------------
         number 手动生成
         userId 当前线程获取
         orderTime 当前时间
         userName ---获取当前登录的微信的用户昵称（做不了）
         phone ---从收货地址中获取
         address---从收货地址中获取，详情地址（省市区+详情）
         consignee ---从收货地址中获取
        */
        //1.查看有没有提交地址信息
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.findById(addressBookId);
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        //2.查看购物车是否存在商品
        Long userId = BaseContext.getCurrentId();
        ShoppingCart options = ShoppingCart.builder().userId(userId).build();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.findByOptions(options);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        String number = System.currentTimeMillis() + "";
        Long id = BaseContext.getCurrentId();
        orders.setUserId(id);
        orders.setNumber(number);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());

        //3.新增订单，返回订单ID
        orderMapper.save(orders);
        //二、根据购物车中商品和前端传递的数据，生成一个或多个订单明细
        //1.查询当前登录用户，获取购物车中商品数据
        //2.把购物车商品数据添加到订单详情列表中（兼容：一个或多个订单详细）
        /*List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }*/
        List<OrderDetail> orderDetailList = shoppingCarts.stream().map(shoppingCart1 -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1, orderDetail);
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());

        //3.完成订单详情的批量插入
        System.out.println(orderDetailList);
        orderDetailMapper.saveBatch(orderDetailList);
        //三、删除购物车中全部（选中）的商品
        shoppingCartMapper.deleteByUserId(id);
        //四、封装返回结果
        return OrderSubmitVO.builder()
                .orderTime(LocalDateTime.now())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .id(orders.getId())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        //暂时不处理
        // 当前登录用户id
        /*Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        WeChatPayUtil weChatPayUtil = new WeChatPayUtil();
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;*/
        return null;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo, String openId) {
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            User user = userMapper.findUserByOpenId(openId);
            userId = user.getId();
        }

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 功能描述: 订单分页
     *
     * @return : com.sky.result.PageResult
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页查询
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.page(ordersPageQueryDTO);

        //设置订单的菜品
        List<OrderVO> collect = page.getResult().stream().map(orders -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            List<OrderDetail> orderDetailList = orderDetailMapper.findByOrdersId(orders.getId());

            //设置订单对应的订单详情
            orderVO.setOrderDetailList(orderDetailList);
            String orderDishes = "";
            for (int i = 0; i < orderDetailList.size(); i++) {
                orderDishes += orderDetailList.get(i).getName();
                if (i != orderDetailList.size() - 1) {
                    orderDishes += ",";
                }
            }

            orderVO.setOrderDishes(orderDishes);
            return orderVO;
        }).collect(Collectors.toList());
        return new PageResult(page.getTotal(), collect);
    }

    /**
     * 功能描述: 查询订单详情
     *
     * @param id
     * @return : com.sky.vo.OrderVO
     */
    @Override
    public OrderVO findOrderDetailsById(Long id) {
        // 返回的数据类型是OrderVO OrderVO包括了 orderDishes Orders OrderDetail(包含了菜品信息、口味) 的属性
        //1.根据order_id    把 Order 查出来
        Orders orders = orderMapper.findOrderByOrderId(id);
        //2.根据 order_id   把 OrderDetail 查出来
        List<OrderDetail> orderDetailList = orderDetailMapper.findOrderDetailByOrderId(id);

        //3.封装 Orders的数据到 OrderVO
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);

        //4.从订单详情里边取菜品详情信息 给orderVO里的orderDishes属性
        String orderDishes = "";
        for (OrderDetail orderDetail : orderDetailList) {
            String name = orderDetail.getName();
            BigDecimal amount = orderDetail.getAmount();
            Integer number = orderDetail.getNumber();
            orderDishes = name + amount + number;

        }
        //5.把orderDishes封装到orderVO里返回
        orderVO.setOrderDishes(orderDishes);
        //6.把orderDetailList 订单详情集合封装到orderVO 返回
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        //根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.findByOrdersId(id);
        //把订单详情转换成购物车对象并存入购物车
        orderDetails.forEach(orderDetail -> {
            //购物车拷贝订单详情
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            //设置当前用户和创建时间
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(userId);
            //存入购物车
            shoppingCartMapper.add(shoppingCart);
        });
    }

    /**
     * 功能描述:  查询订单详情
     *
     * @return : void
     */
    @Override
    public OrderVO findDetailsById(Long id) {
        //根据订单id查询到订单菜品信息
        Orders orders = orderMapper.findOrderByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);

        ////根据订单id查询订单详情并封装进vo
        List<OrderDetail> orderDetails = orderDetailMapper.findByOrdersId(orders.getId());
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 功能描述: 取消订单
     *
     * @param id
     * @return : void
     */
    @Transactional
    @Override
    public OrderSubmitVO CancelId(long id) throws Exception {
        // 根据id查询订单
        Orders ordersId = orderMapper.CancelId(id);
        // 校验订单是否存在
        if (ordersId == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersId.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersId.getId());
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
        return null;
    }


    /**
     * 功能描述: 接单
     *
     * @return : void
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders byId = orderMapper.findOrderByOrderId(ordersConfirmDTO.getId());
        Integer status = byId.getStatus();
        Orders orders = null;
        if (status == Orders.TO_BE_CONFIRMED) {
            orders = Orders.builder()
                    .id(ordersConfirmDTO.getId())
                    .status(Orders.CONFIRMED)
                    .build();
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orderMapper.update(orders);
    }

    /**
     * 功能描述: 拒绝订单，修改订单状态
     *
     * @param ordersRejectionDTO
     * @return : void
     */
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {
        Long id = ordersRejectionDTO.getId();
        Orders ordersById = orderMapper.findOrderByOrderId(id);
        Integer status = ordersById.getStatus();

        //判断订单是否存在
        if (ordersById == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //当订单待接单时可以拒单
        Orders orders = null;
        if (status == Orders.TO_BE_CONFIRMED) {
            orders = Orders.builder()
                    .id(id)
                    .rejectionReason(ordersRejectionDTO.getRejectionReason())
                    .status(Orders.CANCELLED)
                    .cancelTime(LocalDateTime.now()).build();

        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orderMapper.update(orders);
    }

    /**
     * 功能描述: 取消订单
     *
     * @param ordersCancelDTO
     * @return : void
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Long id = ordersCancelDTO.getId();
        Orders ordersById = orderMapper.findById(id);
        Integer status = ordersById.getStatus();
        //判断订单是否存在
        if (ordersById == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Orders orders = null;
        //待付款、待派送、派送中、已完成状态可以进行取消操作
        if (status == Orders.PAID || status == Orders.TO_BE_CONFIRMED || status == Orders.CONFIRMED || status == Orders.DELIVERY_IN_PROGRESS || status == Orders.COMPLETED) {
            orders = Orders.builder()
                    .id(id)
                    .status(Orders.CANCELLED)
                    .cancelReason(ordersCancelDTO.getCancelReason())
                    .cancelTime(LocalDateTime.now()).build();
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orderMapper.update(orders);
    }


    /**
     * 功能描述: 派送订单
     *
     * @param id
     * @return : void
     */
    @Override
    public void delivery(Long id) {
        //1.根据订单id来查询订单
        Orders orders = orderMapper.findOrderByOrderId(id);
        //2.判断订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //3.判断订单是否被接单
        //Integer status = orders.getStatus();
        //if (status != Orders.CONFIRMED){
        //    throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        //}
        //修改状态为派送
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);

    }

    /**
     * 功能描述: 完成订单
     *
     * @return : void
     */

    public void complete(Long id) {
        Orders byId = orderMapper.findOrderByOrderId(id);
        Integer status = byId.getStatus();
        Orders orders;
        if (byId != null && status == Orders.DELIVERY_IN_PROGRESS) {
            orders = Orders.builder()
                    .id(id)
                    .status(Orders.COMPLETED)
                    .build();
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        orderMapper.update(orders);
    }


    /**
     * 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO statistic() {
        OrderStatisticsVO statisticsVO = new OrderStatisticsVO();
        //设置待接单数量
        statisticsVO.setToBeConfirmed(orderMapper.countByStatus(Orders.TO_BE_CONFIRMED));
        //设置待派送数量
        statisticsVO.setConfirmed(orderMapper.countByStatus(Orders.CONFIRMED));
        //设置派送中数量
        statisticsVO.setDeliveryInProgress(orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS));
        return statisticsVO;
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    /**
     * 用户催单
     *
     * @param id
     */
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.findById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

}
